package com.fysports.web.handler;

import cn.jpush.api.utils.Preconditions;
import com.jfinal.handler.Handler;
import com.fysports.web.kit.cache.DictCacheKit;
import com.fysports.web.kit.commons.CookiesKit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 加载缓存内容到request中 此handler慎用，在添加变量时需仔细斟酌。
 * <p>
 * Created by konbluesky Date : 14-8-30 下午7:15 Project : JdmData_WebServer
 */
public class InitTableDictCacheHandler extends Handler {
    /* ftl中使用变量前缀h_ */
    private final static String prefix = "h_";


    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response,
            boolean[] isHandled) {
        /* 百度地图ak */
        putValue(DictCacheKit.DICT_BAIDU_MAP_AK, DictCacheKit.getBaiDuMapAkCode(),request);
        /* 应用名称 */
        putValue(DictCacheKit.DICT_SYSTEM_NAME, DictCacheKit.getSystemName(),request);
        /* 页脚内容 */
        putValue(DictCacheKit.DICT_MAIN_FOOTER, DictCacheKit.getMainFooter(),request);
//        Test Exception msg;
//        putValue(null,null,null);

        /* 从cookie中获取username */
        Cookie author_cookie = CookiesKit.getCookie(request, CookiesKit.COOKIES_AUTHMARK);
        if (author_cookie != null) {
            CookiesKit.CookieVO cvo = CookiesKit.decodeCookieAuthToken(author_cookie.getValue());
            putValue("user_name", cvo.getUsername(), request);
            putValue("user_img", cvo.getUserimg(), request);
        }
        nextHandler.handle(target, request, response, isHandled);
    }


    /**
     * 加载系统常用缓存变量到request attr中。
     * @param key
     * @param value
     * @param request
     */
    private void putValue(String key, String value,HttpServletRequest request) {
        Preconditions.checkNotNull(value,"Dick Cache value [%s] is not null",value);
        String k = prefix + key;
        request.setAttribute(k,value);

    }
}
